<template>
  <div id="cont">
    <div class="cont">
      <p @click="down">下载</p>
    </div>
  </div>
</template>

<script>
import app from '@/utils';

export default {
  name: 'list',
  data() {
    return {

    }
  },
  methods: {
    down() {
			// const formdata = new FormData();
			// const form = document.createElement('form');
			// form.setAttribute('style', 'display:none');
			// form.setAttribute('method', 'post');
			// const input = document.createElement('input');
			// input.setAttribute('type', 'hidden');
			// form.append(input);
			// form.setAttribute('action', '/api/download/file');
			// form.setAttribute('target', '_self');
			// const body = document.createElement('body');
			// body.setAttribute('style', 'display:none');
			// document.body.appendChild(form);
			// form.submit();
			// form.remove();
      console.log('35................');
			const that = this;
			const ajax = new XMLHttpRequest()
				// 很关键
			ajax.responseType = 'blob' 
			ajax.open("POST",'/api/download/file',true)
			//  ajax.setRequestHeader('X-Authorization','Bearer ' + this.$store.state.token)
			ajax.onreadystatechange = function(){
					if(this.readyState == 4) {
						if(this.status == 200) {
							if(this.response.type == "application/octet-stream"){
									that.downloadHandler(this.response)
							}else{
									// 错误提示
									swal('您要下载的资源已被删除！','' , 'error')
							}
						} else if (this.readyState == 2) {
								if(this.status == 200) {
										this.responseType = "blob"
								} else {
										this.responseType = "text"
								}
						}
					}
			}
			ajax.send(null);
			// app.request({
      //   url: '/api/download/file',
      //   method: 'POST',
			// 	// headers:{
      //   //   'Content-Type': 'application/json; application/octet-stream',
			// 	// },
      //   responseType: 'blob',
			// 	success: response => {
			// 		console.log('89...........', response);
			// 		const blob = new Blob([response],{type: "application/octet-stream"});
			// 		console.log('90.............', blob);
					
			// 		const elink = document.createElement('a');
			// 		elink.href = URL.createObjectURL(blob);
      //     elink.download = `251500_avatars.jpeg`;
      //     // elink.setAttribute('download', '251500_avatars.jpeg');
      //     elink.click();
      //     document.body.append(elink)
			// 		// URL.revokeObjectURL(blob);
			// 	}
			// })
    },
    downloadHandler(content) {
			console.log('131............', content);
			
				const nodeA = document.createElement('a')
				nodeA.download = '251500_avatars.jpeg'
				nodeA.style.display = 'none'
				// 字符内容转变成blob Url
				var blob = new Blob([content],{type: "application/octet-stream"})
				nodeA.href = URL.createObjectURL(blob)
				// 点击触发下载
				document.body.appendChild(nodeA)
				nodeA.click()
				// 移除
				// document.body.removeChild(nodeA)
		},
  }
}
</script>